package com.example.manualManagement.service.impl.user.account;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.manualManagement.entity.Manage;
import com.example.manualManagement.mapper.ManageMapper;
import com.example.manualManagement.service.user.account.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private ManageMapper manageMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Map<String, String> register(String userName, String userPassword, String confirmedPassword) {

        Map<String, String> map = new HashMap<>();
        if(userName == null){
            map.put("error_massage", "用户名不能为空");
            return map;
        }

        if(userPassword == null || confirmedPassword == null){
            map.put("error_massage", "密码不能为空");
            return map;
        }

        userName = userName.trim();
        if(userName.length() == 0){
            map.put("error_massage", "用户名不能为空");
            return map;
        }

        if(userPassword.length() == 0 || confirmedPassword.length() == 0){
            map.put("error_massage", "密码不能为空");
            return map;
        }

        if(userName.length() > 20){
            map.put("error_massage", "用户名长度不能大于20");
            return map;
        }

        if(userPassword.length() > 100 || confirmedPassword.length() > 100){
            map.put("error_massage", "密码长度不能大于100");
            return map;
        }

        if(!userPassword.equals(confirmedPassword)){
            map.put("error_massage", "两次输入的密码不一致");
            return map;
        }

        QueryWrapper<Manage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName", userName);
        List<Manage> users = manageMapper.selectList(queryWrapper);
        if(!users.isEmpty()){
            map.put("error_massage", "用户名已经存在");
            return map;
        }

        String encodedPassword = passwordEncoder.encode(userPassword);
        Manage manage = new Manage(null, userName, encodedPassword);
        manageMapper.insert(manage);

        map.put("error_massage", "success");
        return map;
    }
}
